package com.util.common.encoding;

import info.monitorenter.cpdetector.io.ASCIIDetector;
import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;
import info.monitorenter.cpdetector.io.ParsingDetector;
import info.monitorenter.cpdetector.io.UnicodeDetector;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.charset.Charset;

public class FileCode {
	
	private static FileCharsetDetector charsetDetector = new FileCharsetDetector();
	
	public static String getFileCodeName(String filePath) throws MalformedURLException, IOException{
		CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
		detector.add(new ParsingDetector(false));
		detector.add(JChardetFacade.getInstance());
		detector.add(ASCIIDetector.getInstance());
		detector.add(UnicodeDetector.getInstance());
		Charset charset = null;
		File file = new File(filePath);
		charset = detector.detectCodepage(file.toURL());
		String codeName = (charset == null) ? null : charset.name();
		return codeName;
	}
	
	public static String getFileCodeName(InputStream inputStream) throws IllegalArgumentException, IOException{
		CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
		detector.add(new ParsingDetector(false));
		detector.add(JChardetFacade.getInstance());
		detector.add(ASCIIDetector.getInstance());
		detector.add(UnicodeDetector.getInstance());
		Charset charset = null;
		charset = detector.detectCodepage(inputStream, 100);
		String codeName = (charset == null) ? null : charset.name();
		return codeName;
	}
	
	public static String guestStreamEncoding(InputStream inputStream) throws IOException{
		return charsetDetector.guestStreamEncoding(inputStream);
	}
	
}
